package com.twt.recruit.service;

import com.twt.recruit.entity.vo.TimeSlot;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class InterviewScheduler {
    private List<TimeSlot> timeSlots;

    public InterviewScheduler(List<TimeSlot> timeSlots) {
        this.timeSlots = timeSlots;
    }

    public List<List<TimeSlot>> scheduleInterviews(int numberOfDays) {
        List<List<TimeSlot>> scheduledInterviews = new ArrayList<>();
        for (int i = 0; i < numberOfDays; i++) {
            scheduledInterviews.add(new ArrayList<>());
        }

        // 构建每个 uid 对应的合适的 time_section
        Map<Integer, String> suitableTimeSectionsPerUid = new HashMap<>();
        for (TimeSlot timeSlot : timeSlots) {
            suitableTimeSectionsPerUid.put(timeSlot.getApplicationId(), timeSlot.getTimeSection());
        }

        // 平均分配时间段到每天
        int currentDay = 0;
        for (Map.Entry<Integer, String> entry : suitableTimeSectionsPerUid.entrySet()) {
            int uid = entry.getKey();
            String timeSection = entry.getValue();
            int slotsPerDay = (int) Math.ceil(timeSlots.stream().filter(ts -> ts.getApplicationId() == uid).count() / (double) numberOfDays); // 每天应分配的时间段数量

            for (int i = 0; i < timeSlots.size(); i++) {
                TimeSlot timeSlot = timeSlots.get(i);
                if (timeSlot.getApplicationId() == uid && timeSlot.getTimeSection() == timeSection) {
                    int day = currentDay % numberOfDays;
                    scheduledInterviews.get(day).add(timeSlot); // 添加面试时间段
                    if (scheduledInterviews.get(day).size() == slotsPerDay) {
                        currentDay++;
                    }
                }
            }
        }

        return scheduledInterviews;
    }
}
